package com.myhome.controller;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myhome.config.constant.R;
import com.myhome.domain.SysRole;
import com.myhome.service.SysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import java.util.Arrays;

/**
 * @Author QYiXin
 * @Date 2021 10 10 12 20
 **/
@RestController
@Api(tags = "角色相关操作")
@RequestMapping("/roles")
public class SysRoleController {
    @Autowired
    SysRoleService sysRoleService;

    @GetMapping
    @ApiOperation("获取相关角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "当前页数据数目")
    })
    @PreAuthorize("hasAuthority('sys_role_query')")
    public R<Page<SysRole>> getAllRoles(@ApiIgnore Page<SysRole> page,String name) {
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<SysRole> result = sysRoleService.queryByName(page, name);
        return R.ok(result);
    }

    @PostMapping
    @ApiOperation("新增角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysRole", value = "角色数据")
    })
    @PreAuthorize("hasAuthority('sys_role_create')")
    public R insertPrivilege(@RequestBody @Validated SysRole sysRole) {
        boolean isSave = sysRoleService.save(sysRole);
        if (isSave) {
            return R.ok("新增成功");
        }
        return R.fail("新增失败");
    }

    @PostMapping("/delete")
    @ApiOperation("删除角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids",value = "删除角色得id集合")
    })
    @PreAuthorize("hasAuthority('sys_role_delete')")
    public R deleteRole(@RequestBody String[] ids){
        if (ids.length == 0 || ids == null) {
            return R.fail("删除数据不能为空");
        }
        boolean isRemove = sysRoleService.removeByIds(Arrays.asList(ids));
        if (isRemove) {
            return R.ok("删除成功");
        }
        return R.fail("删除失败");
    }
}
